<?php
/**
 * @package PWE.modele
 * @author Gmax <gmaxfr78@gmail.com>
 */
class modele_media extends modele {
    protected static $_table = 'media';
    private $_id = 0;
    private $_title = '';
    private $_path = '';
    private $_media_type_id = 1;
    private $_media_type = '';
    private $_width = 0;
    private $_height = 0;
    private $_legende = '';
    
    public $type = 'media';
    
    function __construct($id=null){
        if($id!==null){
            $this->_constructObject($id);
        }
    }
    private function _constructObject($modele_id){
        $sqlQuery = 'SELECT ';
        $sqlQuery .= 't.*, ';
        $sqlQuery .= 'm.nom AS media_type ';
        $sqlQuery .= 'FROM '.self::getTable().' as t ';
        $sqlQuery .= 'LEFT JOIN '.PWE::getPrefixBdd().'media_type AS m ON m.id=t.media_type_id ';
        $sqlQuery .= 'WHERE t.id='.$modele_id.' ';
        $sqlQuery .= 'LIMIT 1';
        
        $datas = $this->_getOneResult($sqlQuery);
        if($datas){
            $this->_id = $datas['id'];
            $this->_title =  $datas['title'];
            $this->_path =  $datas['path'];
            $this->_media_type_id = $datas['media_type_id'];
            $this->_media_type = $datas['media_type'];
            $this->_width = $datas['width'];
            $this->_height = $datas['height'];
            $this->_legende = $datas['legende'];
        }
    }
    public function getId(){
        return $this->_id;
    }
    public function getTitle($input=false){
        if($input)return $this->inputFormat($this->_title);
        else return $this->outputFormat($this->_title);
    }
    
    /**
     * renvoi le nom de fichier
     * @param string $prefix
     * @param boolean $ext indique si on renvoi le nom avec l'extension
     * @return string
     */
    public function getFileName($prefix='',$ext=true){
        $url = $this->getUrl($prefix);
        $fileName = substr($url, strrpos($url, '/')+1);
        
        if(!$ext){
            $fileName = substr($fileName, 0, strrpos($fileName, '.'));
        }
        
        return $fileName;
    }
    /**
     * renvoi l'extension du fichier avec le .
     * @param string $prefix
     * @return string
     */
    public function getFileExt($prefix=''){
        $fileName = $this->getFileName($prefix);
        $ext = substr($fileName, strrpos($fileName, '.'));
        return $ext;
    }
    
    public function setPath($string){
        $this->_path = $string;
    }
    public function getPath(){
        if($this->_path==null||$this->_path==''){
            return PWE::getMissingMedia();
        }else{
            return $this->_path;
        }
    }
    /**
     * renvoi l'url du media
     * @param string $prefix
     * @return string
     */
    public function getUrl($prefix=''){
        if(!file_exists($prefix.$this->getPath())){
            return PWE::getBaseURL().PWE::getMissingMedia();
        }
        return PWE::getBaseURL().$this->getPath();
    }
    /**
     * renvoi
     * @param string $prefix
     * @param int $maxWidth
     * @param int $maxHeight
     * @return string
     */
    public function getThumbUrl($prefix='',$maxWidth=150,$maxHeight=150){
        if(!file_exists($prefix.$this->getPath())){
            return PWE::getBaseURL().PWE::getMissingMedia();
        }
        if($this->getMediaType()!=='image' || ($maxWidth==0&&$maxHeight==0)){
            return PWE::getBaseURL().$this->getPath();
        }
        // génération de la vignette
        $nameThumb = $this->getFileName($prefix, false).'-'.$maxWidth.'x'.$maxHeight.$this->getFileExt($prefix);
        
        $path = str_replace($this->getFileName($prefix), 'thumbnails/'.$nameThumb, $this->getPath($prefix));
        if(file_exists($path)){
            return PWE::getBaseURL().$path;
        }else{
            // générer la vignette
            $uploader = new controler_upload('uploads/',$prefix);
            $uploader->loadFile($this->getPath($prefix), $this->getFileName($prefix));
            $uploader->resizeImage($maxWidth, $maxHeight);
            $uploader->saveFile($nameThumb,'images/thumbnails/');
        }
        return PWE::getBaseURL().$path;
    }
    
    public function getMediaTypeId(){
        return $this->_media_type_id;
    }
    /**
     * generation d'un permalien fantome pour compatibilité générale
     * @return \modele_permalien
     */
    public function getPermalien(){
        $permalien = new modele_permalien();
        $permalien->setDatas(array(
            '_modele'=>'media',
            '_modele_id'=>$this->getId(),
            'lien'=>$this->getPath()
        ));
        return $permalien;
    }
    /**
     * retourne le type de media : image|pdf
     * @param type $input
     * @return string
     */
    public function getMediaType($input=false){
        return $this->_media_type;
    }
    public function getWidth(){
        return $this->_width;
    }
    public function getHeight(){
        return $this->_height;
    }
    public function getLegende($input=false){
        if($input)return $this->inputFormat($this->_legende);
        else return $this->outputFormat($this->_legende);
    }
    public function getDatas($input=false){
        $data = array();
        $data['id'] = $this->getId();
        $data['title'] = $this->getTitle($input);
        $data['path'] = $this->getPath();
        $data['url'] = $this->getUrl();
        $data['media_type_id'] = $this->getMediaTypeId();
        $data['media_type'] = $this->getMediaType($input);
        $data['width'] = $this->getWidth();
        $data['height'] = $this->getHeight();
        $data['legende'] = $this->getLegende($input);
        return $data;
    }
    public function setDatas($datas){
        foreach($datas as $k=>$v){
            if($k != '_id' && property_exists('modele_media',$k)){
                $this->$k = $v;
            }
        }
        return true;
    }
    public function save() {
        $sqlQuery = 'INSERT INTO '.self::getTable().' ';
        $sqlQuery .= '(title,path,media_type_id,width,height,legende) ';
        $sqlQuery .= 'VALUES (';
        $sqlQuery .= '"'.$this->getTitle(true).'", ';
        $sqlQuery .= '"'.$this->getPath().'", ';
        $sqlQuery .= $this->getMediaTypeId().', ';
        $sqlQuery .= $this->getWidth().', ';
        $sqlQuery .= $this->getHeight().', ';
        $sqlQuery .= '"'.$this->getLegende(true).'"';
        $sqlQuery .= ')';
        
        bdd_sql::doSql($sqlQuery,false);
        $this->_id = bdd_sql::getLastInsertId();
        
        return array('success'=>true,'datas'=>$this->getDatas());
    }
    public function update() {
        $sqlQuery = 'UPDATE '.self::getTable().' SET ';
        $sqlQuery .= 'title="'.$this->getTitle(true).'", ';
        $sqlQuery .= 'path="'.$this->getPath().'", ';
        $sqlQuery .= 'media_type_id='.$this->getMediaTypeId().', ';
        $sqlQuery .= 'width='.$this->getWidth().', ';
        $sqlQuery .= 'height='.$this->getHeight().', ';
        $sqlQuery .= 'legende="'.$this->getLegende(true).'" ';
        $sqlQuery .= 'WHERE id='.$this->_id.' LIMIT 1';
        bdd_sql::doSql($sqlQuery,false);
        
        return array('success'=>true,'datas'=>$this->getDatas());
    }
    
    public function delete() {
        $sqlQuery = 'DELETE FROM '.self::getTable().' WHERE id='.$this->getId();
        bdd_sql::doSql($sqlQuery,false);
        
        // suppression du fichier
        if(file_exists($this->getPath())){
            unlink($this->getPath());
        }elseif(file_exists('../'.$this->getPath())){
            unlink('../'.$this->getPath());
        }elseif(file_exists('../../'.$this->getPath())){
            unlink('../../'.$this->getPath());
        }
        return array('success'=>true,'datas'=>array());
    }
    
    /* methodes statiques */
    /**
     * 
     * @return string
     */
    public static function getTable(){
        return PWE::getPrefixBdd().self::$_table;
    }
    
    public static function getListe($start = 0){
        $sqlQuery = 'SELECT id FROM '.self::getTable().' ORDER BY id DESC';
        if($start>0){
            $sqlQuery .=  ''; // TODO pagination
        }
        $retour = array();
        $results = bdd_sql::doSql($sqlQuery,true);
        if($results['count']>0){
            foreach($results['results'] as $mediaData){
                $retour[] = new modele_media($mediaData['id']);
            }
        }
        return $retour;
    }
}

?>